import Vue from 'vue'
import axios from 'axios'
import store from '@/vuex'
import globalSetting from '@/config.js'
import {
	showSuccess,
	showModal
} from '@/utils/common.js' //公共方法
import {
	getToken
} from '@/utils/auth'

const service = axios.create({
	baseURL: globalSetting.domain,
	// withCredentials: true, // send cookies when cross-domain requests
	timeout: 10000,
	adapter: config => { //自定义适配器
		return new Promise((resolve, reject) => {
			var settle = require('axios/lib/core/settle');
			var buildURL = require('axios/lib/helpers/buildURL');
			uni.request({
				method: config.method.toUpperCase(),
				url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
				header: config.headers,
				data: config.data,
				dataType: config.dataType,
				responseType: config.responseType,
				sslVerify: config.sslVerify,
				complete: function complete(response) {
					response = {
						data: response.data,
						status: response.statusCode,
						errMsg: response.errMsg,
						header: response.header,
						config: config
					};
					settle(resolve, reject, response);
				},
				fail: err => {}
			})
		})
	}
})

//请求拦截器
service.interceptors.request.use(
	config => {
		if (store.getters.token) {
			config.headers['Authorization'] = getToken();
		}
		return config
	},
	error => {
		return Promise.reject(error)
	}
)

//响应拦截器
service.interceptors.response.use(
	response => {
		const res = response.data;
		if (res.code == 600 || res.code == 602) { // 600, "登录过期,请重新登录"；602, "Token验证失败"
			store.dispatch('user/resetToken').then(() => {
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/register/login'
					})
				}, 500)
			})
			return Promise.reject(new Error(res.msg || '系统繁忙，请稍后再试！'))
		} 
		else if (res.code == 200) {
			return res
		} else {
			// 都是错误情况
			uni.showToast({
				title: res.msg,
				icon: 'none'
			});
			return Promise.reject(new Error(res.msg || '系统繁忙，请稍后再试！'))
		}

	},
	error => {
		uni.showToast({
			title: error.message,
			icon: 'none'
		});
		return Promise.reject(error)
	}
)
export default service